//
//  PaymentMethodVC.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/3/3.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "PaymentMethodVC.h"
#import "PaymentMethodCell.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <AlipaySDK/AlipaySDK.h>
#import "HeaderMacro.h"
#import "DLLApiManager.h"
#import "WXApi.h"
#import <QXDataManager/QXDataManager.h>
#import "ConfigureKeyHeader.h"
#import "AppInfoModel.h"
#import "AppManager.h"
#import <QXYueYueModels/QXYYUserDriverModel.h>

#import "NotificationNameManager.h"

#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"
#import "AppManager.h"
#import "AppInfoModel.h"
@interface PaymentMethodVC ()<UITableViewDelegate , UITableViewDataSource , WXApiDelegate>

/**
 支付的总的费用
 格式: *元
 */
@property (weak, nonatomic) IBOutlet UILabel *totalFare;

@property (weak, nonatomic) IBOutlet UITableView *tableView;


/**
 关闭按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *closeButton;

@property(nonatomic , strong) NSArray *imageNameArray;
@property(nonatomic , strong) NSArray *titleNameArray;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomMargin;

@property (weak, nonatomic) IBOutlet UIView *popView;

/// 标题label例如: 收到乘客现金支付后,您可以选择以下方式代付车费
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

PaymentMethodVC *paymentMethodVCReturn = nil;
@implementation PaymentMethodVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configureDefaultAttributes];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}

+ (PaymentMethodVC *)returnSelf {
    
    return paymentMethodVCReturn;
}

/**
 初始化默认属性
 */
- (void)configureDefaultAttributes {
    
    
    AppManager *appManager = [AppManager shareManager];
    AppInfoModel *appInfoModel = [appManager getAppInfo];
    if (appInfoModel.AppDriverOrgan == AppDriverOrganNameOfKuaiJie || appInfoModel.AppDriverOrgan == AppDriverOrganNameOfMiaoSheng || appInfoModel.AppDriverOrgan == AppDriverOrganNameOfHuiYue) { // 快捷,汇约,妙盛没有微信支付
        
        self.imageNameArray = @[@"public_pic_zhifubao" , @"public_pic_yuezhifu"];
        self.titleNameArray = @[@"支付宝支付" , @"余额支付"];
    }else {
        
        self.imageNameArray = @[@"public_pic_weixinzhifu" , @"public_pic_zhifubao" , @"public_pic_yuezhifu"];
        self.titleNameArray = @[@"微信支付" , @"支付宝支付" , @"余额支付"];
    }
    
    self.totalFare.text = [NSString stringWithFormat:@"%@元" , self.totalPay];

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[QXDriverConfiguration imageWithName:@"nav_icon_back_white"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction:)];
    
    [self.closeButton setImage:[QXDriverConfiguration imageWithName:@"public_close"] forState:(UIControlStateNormal)];
}

- (void)backAction:(UIBarButtonItem *)barBut {
    
    [self dismiss];
}

+ (PaymentMethodVC *)presentVC {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Orders" bundle:[NSBundle mainBundle]];
    
    PaymentMethodVC *paymentMethodVC = [storyboard instantiateViewControllerWithIdentifier:@"PaymentMethodVCID"];
    paymentMethodVCReturn = paymentMethodVC;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow.rootViewController addChildViewController:paymentMethodVC];
    [keyWindow.rootViewController.view addSubview:paymentMethodVC.view];
    paymentMethodVC.bottomMargin.constant = -250;
    [paymentMethodVC.view layoutIfNeeded];
    
    
    NSString *titleStr = @"收到乘客现金支付后,您可以选择以下方式代付车费";
    
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
     
        titleStr = @"收到用户现金支付后,您可以选择以下方式代付车费";
    }
    paymentMethodVC.titleLabel.text = titleStr;
    
    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
       
        paymentMethodVC.bottomMargin.constant = 0;
        [paymentMethodVC.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        
    }];
    
    return paymentMethodVC;
}

- (void)dismiss {
    
    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
        
        
        self.bottomMargin.constant = -250;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        paymentMethodVCReturn = nil;
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.imageNameArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    cell = [self dealPWithPaymentMethodCell:tableView indexPath:indexPath];
    return cell;
}

- (PaymentMethodCell *)dealPWithPaymentMethodCell:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    PaymentMethodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PaymentMethodCellID" forIndexPath:indexPath];
    
    NSString *imageName = self.imageNameArray[indexPath.row];
    NSString *titleName = self.titleNameArray[indexPath.row];
    
    [cell setValueWithImageName:imageName titleName:titleName];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AppManager *appManager = [AppManager shareManager];
    AppInfoModel *appInfoModel = [appManager getAppInfo];
    if (appInfoModel.AppDriverOrgan == AppDriverOrganNameOfKuaiJie || appInfoModel.AppDriverOrgan == AppDriverOrganNameOfMiaoSheng || appInfoModel.AppDriverOrgan == AppDriverOrganNameOfHuiYue) { // 快捷,妙盛,汇约没有微信支付
        
        switch (indexPath.row) {
            case 0: { // 阿里支付
    
                [self aliPay];
                break;
            }
            case 1: { //余额支付
    
                [self yuePay];
                break;
            }
            default:
                break;
        }
        
    }else {
        
        switch (indexPath.row) {
            case 0: { // 微信支付
                
                [self weixinPay];
                break;
            }
            case 1: { // 支付宝支付
                
                [self aliPay];
                break;
            }
            case 2: { // 余额支付
                
                [self yuePay];
                break;
            }
            default:
                break;
        }
    }
}


/**
 支付宝支付发起方法
 */
- (void)aliPay {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.orderUuid forKey:@"orderUuid"];
    
    [DLLApiManager aliPayWithParameters:params success:^(id data) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });
        
        
        if (NetWork_Success) {
            
            NSString *orderString = data[@"data"];
            
            if (orderString) {
                // 主线程执行
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self alipayWithOrderString:orderString];
                });
            }
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:KeyWord_OrderCreatedFailed onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = YES;
        });
    }];
    
}

// 支付宝支付方法
- (void)alipayWithOrderString:(NSString *)orderString {
    
    AppInfoModel *appInfoModel = [[AppManager shareManager] getAppInfo];
//    NSString *urlScheme = AliPayCallBackUrlSchemes;
    NSString *urlScheme = appInfoModel.AppAliPayCallBackValue;
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:urlScheme callback:^(NSDictionary *resultDic) {
        
        // 注释这里的回调并没有什么卵用,支付宝支付成功的回调在AppDeletgate文件里面处理
        
        
        
        // 支付失败
        NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
        if (resultStatus == 6001) {
            
            // 支付失败
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD showWithText:KeyWord_OrderDealFailed onView:self.view hiddenDuration:2.0];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
            });
        } else if (resultStatus == 9000) {
            
            // 支付成功
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD showWithText:KeyWord_OrderDealSuccess onView:nil hiddenDuration:2.0];
                [self.navigationController popViewControllerAnimated:NO];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PaySuccess object:nil];
                [self dismiss];
            });
        } else {
            
            // 支付失败
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
            });
        }
    }];
}


/**
 微信支付发起方法
 */
- (void)weixinPay {
    
    //判断是否有安装微信，没有则提示
    if (![WXApi isWXAppInstalled]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"支付失败，您没有安装微信客户端" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });

        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.orderUuid forKey:@"orderUuid"];
    
    NSString *ipAddress = [self getIPAddress:YES];
    [parameters setValue:ipAddress forKey:@"spbillCreateIp"];
    
    [DLLApiManager wxPayWithParameters:parameters success:^(id data) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            NSString *appid = [[data valueForKey:@"data"] valueForKey:@"appid"];
            NSString *noncestr = [[data valueForKey:@"data"] valueForKey:@"noncestr"];
            NSString *package = [[data valueForKey:@"data"] valueForKey:@"pkg"];
            NSString *partnerid = [[data valueForKey:@"data"] valueForKey:@"partnerid"];
            NSString *prepayid = [[data valueForKey:@"data"] valueForKey:@"prepayid"];
            NSString *timestamp = [[data valueForKey:@"data"] valueForKey:@"timestamp"];
            NSString *serversign = [[data valueForKey:@"data"] valueForKey:@"sign"];
            
            //调起微信支付
            PayReq *req     = [[PayReq alloc] init];
            req.openID      = appid;
            req.partnerId   = partnerid;
            req.prepayId    = prepayid;
            req.nonceStr    = noncestr;
            req.timeStamp   = timestamp.intValue;
            req.package     = package;
            req.sign        = serversign;
            // 主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [WXApi sendReq:req]; // 发起支付
            });
            
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:KeyWord_OrderCreatedFailed onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = YES;
        });
    }];
}
        
#pragma mark - 获取设备当前网络IP地址
- (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ? @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] : @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         //筛选出IP地址格式
         if([self isValidatIP:address]) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

- (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
    
    if (regex != nil) {
        NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
        
        if (firstMatch) {
//            NSRange resultRange = [firstMatch rangeAtIndex:0];
//            NSString *result=[ipAddress substringWithRange:resultRange];
            
            return YES;
        }
    }
    return NO;
}

- (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

/**
 余额支付
 */
- (void)yuePay {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    });
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.orderUuid forKey:@"orderUuid"];
    [DLLApiManager yuePayWithParameters:parameters success:^(id data) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:nil hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                [self.navigationController popViewControllerAnimated:NO];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PaySuccess object:nil];
                [self dismiss];
            });
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
            });
        }
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
        });
    }];
}


#pragma mark - WXApiDelegate
///微信客户端回调
-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode) {
            case WXSuccess: {
                //支付成功
                // 主线程
                dispatch_async(dispatch_get_main_queue(), ^{

                    MBProgressHUD *mb = [MBProgressHUD showWithText:@"支付成功" onView:nil hiddenDuration:2.0];
                    mb.userInteractionEnabled = NO;
                    [self.navigationController popViewControllerAnimated:NO];
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PaySuccess object:nil];
                    [self dismiss];
                });
                break;
            }
                
            default: {
                //支付失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    MBProgressHUD *mb = [MBProgressHUD showWithText:@"支付失败" onView:self.view hiddenDuration:2.0];
                    mb.userInteractionEnabled = NO;
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
                });
                
                break;
            }
        }
    }
}


#pragma mark - setter 方法
- (void)setTotalPay:(NSString *)totalPay {
    
    _totalPay = totalPay;
    self.totalFare.text = [NSString stringWithFormat:@"%@元" , totalPay];
}


#pragma mark - 关闭action
- (IBAction)closeAction:(UIButton *)sender {
    

    [self dismiss];
}

- (void)dealloc {
    
    NSLog(@"支付方式页面销毁了");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
